<template>
  <div style="font-size: 14px;">
    <div id="goods">
      <div id="emptyCart" v-if="cartList.length === 0">
        <p id="empty">购物车是空的</p>
        <a @click="toType" class="" id="goShopping">去逛逛</a>
      </div>

      <div class="goods-list" v-for="(item,index) in cartList" :key="index">
        <a class="select">
          <van-checkbox v-model="item.checked" @change="selected(item)" checked-color="#ee0a24"> </van-checkbox>
        </a>
        <div class="goods-img" @click="productDetail(item)">
          <img :src="require('../../assets/img/'+item.img)">
        </div>
        <div class="goods-info">
          <p @click="productDetail(item)">{{item.productName}}</p>
          <div class="goods-count">
            <p @click="productDetail(item)">￥{{item.price}}</p>
            <div class="goods-num">
              <a>
                <img @click="subNum(item)" src="../../assets/img/sub.png">
              </a>
              <span>{{item.num}}</span>
              <a>
                <img @click="addNum(item)" src="../../assets/img/add.png">
              </a>
            </div>
            <div class="delete">
              <a @click="delCartSingle(index)">
                <img src="../../assets/img/del.png">
              </a>
            </div>
          </div>
        </div>
      </div>

      <div id="accounts">
        <div id="accounts-content">
          <a>
            <van-checkbox v-model="allChecked" @change="selectAll" checked-color="#ee0a24" class="allChecked"> </van-checkbox>
            <p>全选</p>
          </a>
          <p>
            <span>合计:</span>
            <span class="total-price"> ￥{{totalPrice.toFixed(2)}}</span>
          </p>
          <a v-if="totalNum === 0" style="background: rgb(204, 204, 204);">结算(0)</a>
          <a v-else style="background: #ff6034;" @click="toPay">结算({{totalNum}})</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {getStore,setStore,removeStore} from "@/store/store.js";
  import { Checkbox, CheckboxGroup, Dialog } from 'vant';
  export default {
    
    components: {
      [Checkbox.name]: Checkbox,
      [CheckboxGroup.name]: CheckboxGroup,
      [Dialog.Component.name]: Dialog.Component,
    },

    data() {
      return {
        cartList:[],//购物车数据
        allChecked: true,//全部选中
        totalNum: 0,
        totalPrice: 0,
      };
    },

    mounted() {
      this.$store.commit('SET_HEADER_FOOTER', {showSearchHeader: true,headerName:'购物车',pageName:'cart',showFooter: true});
      this.initCart();
    },

    methods: {
      toType(){//跳转分类
        this.$router.push({'path': '/type'});
      },
      //初始化购物车
      initCart(){
        let cartList = getStore({name:'cart_list'});
        if (cartList) {
          cartList.forEach((item,index)=>{
            item['checked'] = true;
          });
          this.allChecked = true;
          this.cartList = cartList;
          console.log(this.cartList);
          this.total();
        }
      },
      //统计
      total() {
        this.totalNum = 0;
        this.totalPrice = 0
        this.cartList.forEach((item) => {
          item.checked ? (this.totalNum += item.num) : (this.totalNum += 0)
          item.checked ? (this.totalPrice += item.num * item.price) : (this.totalPrice += 0);
        })
      },
      //缓存购物车
      saveCarToStorage(){
        setStore({name:'cart_list',content: this.cartList});
        this.total();
        console.info(this.cartList);
      },
      //删除购物车商品 - 单个
      delCartSingle(index){
        this.$dialog.confirm({
          title: '提示',
          message: '确定删除？',
        })
        .then(() => {
          if(this.cartList.length > index){
            //删除
            this.cartList.splice(index,1);
          }
          try {
            //存到缓存
            this.saveCarToStorage();
            this.$toast.success('删除成功');
          } catch (e) {
            this.$toast.fail('删除失败');
          }
        })
        .catch(() => {
          // on cancel
        });
      },
      //删除购物车商品 - 全部
      delCartAll(index){
        try {
          removeStore({name:'cart_list'});
          this.$toast.success('删除成功');
          this.initCart();
        } catch (e) {
          this.$toast.fail('删除失败');
        }
      },
      //商品详情
      productDetail(item) {
        console.info(item);
        this.$router.push({
          path:'/productDetail',
          query:{
            id: item.id
          }
        })
      },
      //勾选商品
      selected(item){
        // item.checked = !item.checked;
        if (!item.checked) {
          this.allChecked = false;
        } else {
          let allChecked = true;
          this.cartList.forEach((item) => {
            if(!item.checked){
              allChecked = false;
            }
          })
          this.allChecked = allChecked;
        }
        this.total();
      },
      //全选
      selectAll(){
        if (this.allChecked) {
          this.cartList.map((item) => {
            this.checked = true;
            item.checked = true;
          })
        } else {
          this.checked = false;
          this.cartList.map((item) => {
            item.checked = false;
          })
        }
        this.total();
      },
      subNum(item){
        let num=item.num;
        if(num>1){
          num-=1
        }
        item.num=num;
        //存到缓存
        this.saveCarToStorage();
      },
      addNum(item){
        let num =item.num;
        item.num=num+1;
        //存到缓存
        this.saveCarToStorage();
      },
      //结算
      toPay() {
        let value = '';
        this.cartList.forEach((item) => {
          if(item.checked){
            if(value !== ''){
              value += '*';
            }
            value += item.id + '_' + item.num;
          }
        });
        this.$router.push({
          path:'/pay',
          query:{
            value: value
          }
        })
      },
    }
  };
</script>
<style scoped>
  #goods {
    padding: 0rem 0 6.2rem 0;
  }
  #emptyCart {
    background: #e9e9e9;
    width: 100vw;
    height: 30vw;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  #empty {
    color: #bfbfbf;
    margin-right: 0.5rem;
  }
  li, p, ul {
    margin: 0;
  }
  #goShopping {
    color: #696969;
    padding: 0.15rem 0.5rem;
    border: 0.05rem solid #bfbfbf;
    border-radius: 0.2rem;
  }
  a {
    text-decoration: none;
    color: #000;
  }
  #accounts {
    position: fixed;
    z-index: 2;
    bottom: 3.2rem;
    left: 0;
    background: #fff;
  }
  #accounts-content, #accounts-content a:first-child {
    display: flex;
    align-items: center;
  }
  #accounts-content {
    justify-content: space-between;
    width: 100vw;
    height: 3rem;
    box-sizing: border-box;
    border-top: 0.03rem solid #e9e9e9;
    font-size: .9rem;
  }
  #accounts-content, #accounts-content a:first-child {
    display: flex;
    align-items: center;
  }
  a {
    text-decoration: none;
    color: #000;
  }
  #accounts-content img {
    height: 1.3rem;
    width: 1.3rem;
    padding: 0.7rem;
  }
  .total-price {
    color: #ff6700;
    font-size: 16px;
    font-weight: 600;
  }
  #accounts-content a:last-child {
    width: 30vw;
    height: 3rem;
    background: #ff6700;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #e9e9e9;
    text-decoration: none;
  }
  .goods-list {
    display: flex;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 0.3rem solid #e9e9e9;
  }
  .select {
    margin: 0 10px;
  }
  .goods-img img {
    width: 3rem;
    height: 3rem;
    border: 0.05rem solid #e9e9e9;
    padding: 0.5rem;
    margin-right: 0.7rem;
    display: block;
  }
  .goods-info {
    width: calc(100vw - 9rem);
  }
  .goods-info>p {
    margin: 0 0 1rem 0;
  }
  .goods-count {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .goods-count p:first-child {
    color: #ff6700;
    width: 4rem;
    font-size: .9rem;
  }
  .goods-num {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .goods-num img, .goods-num span {
    width: 1rem;
    height: 1rem;
    padding: 0.2rem;
  }
  .goods-num img {
    display: block;
    border: 0.03rem solid #d9d9d9;
  }
  .goods-num span {
    display: inline-block;
    font-size: 1rem;
    line-height: 1rem;
    text-align: center;
    border-top: 0.03rem solid #d9d9d9;
    border-bottom: 0.03rem solid #d9d9d9;
  }
  .delete img {
    display: block;
    width: 1.2rem;
    height: 1.2rem;
  }
  .allChecked{
    margin: 0 10px;
  }
</style>
